<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <div class="">
      <div class="p-2 text-right">
        <a-button type="primary" @click="handleAdd" size="small">新增</a-button>
      </div>
      <Table :dataSource="list" :columns="columns" :pagination="false">
        <template #tztj="{ record, index }">
          <div class="flex">
            <Select
              :options="firstBracketOptions"
              v-model:value="record['firstBracket']"
              class="w-80px"
              style="margin-right: 5px"
              :get-popup-container="getPopupContainer"
            />

            <Select
              :options="formGetFieldsData"
              v-model:value="record['fieldName']"
              class="w-200px"
              style="margin-right: 5px"
              optionFilterProp="label"
              showSearch
              @change="handleFieldNameChange($event, record)"
              :get-popup-container="getPopupContainer"
            />
            <Select
              :options="compareOptions3"
              v-model:value="record['compare']"
              class="w-100px"
              style="margin-right: 5px"
              v-if="record['fieldName'] == 'cws_status'"
              :get-popup-container="getPopupContainer"
            />
            <!-- compareOptions4 -->
            <Select
              :options="compareOptions3"
              v-model:value="record['compare']"
              class="w-100px"
              style="margin-right: 5px"
              v-else-if="
                record['fieldName'] == 'cws_flag' ||
                record['fieldType'] == FormField.FIELD_TYPE_TEXT ||
                record['fieldType'] == FormField.FIELD_TYPE_VARCHAR
              "
              :get-popup-container="getPopupContainer"
            />
            <Select
              :options="compareOptions"
              v-model:value="record['compare']"
              class="w-100px"
              style="margin-right: 5px"
              :get-popup-container="getPopupContainer"
              v-else
            />

            <Select
              :options="columnNameOptions1"
              v-model:value="record['columnName']"
              class="w-100px"
              style="margin-right: 5px"
              v-if="record['fieldName'] == 'cws_status'"
              :get-popup-container="getPopupContainer"
            />
            <Select
              :options="columnNameOptions2"
              v-model:value="record['columnName']"
              class="w-100px"
              style="margin-right: 5px"
              v-else-if="record['fieldName'] == 'cws_flag'"
              :get-popup-container="getPopupContainer"
            />
            <!-- <Select
              :options="formGetFieldsMainData"
              v-model:value="record['columnName']"
              class="w-200px"
              style="margin-right: 5px"
              optionFilterProp="label"
              showSearch
              v-if="record['fieldName'] == 'mainFormOpt'"
            /> -->

            <div
              class="w-150px"
              style="margin-right: 5px"
              v-else-if="
                record['fieldName'] != 'cws_status' &&
                record['fieldName'] != 'cws_flag' &&
                record['fieldName'] != 'mainFormOpt'
              "
            >
              <Input
                v-if="
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_DATE) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_YEAR) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_MONTH) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_USER) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_USER_ROLE) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_USER_DEPT) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_USER_DEPT_AND_CHILDREN) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_ADMIN_DEPT) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_MAIN_ID) == 0
                "
                v-model:value="record['columnName']"
                :readonly="
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_DATE) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_YEAR) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_MONTH) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_USER) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_USER_ROLE) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_USER_DEPT) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_USER_DEPT_AND_CHILDREN) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_ADMIN_DEPT) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_MAIN_ID) == 0
                "
              />
              <FormCtl
                v-else-if="record['fieldName'] && record['formCode']"
                :formCode="record['formCode']"
                :fieldName="record['fieldName']"
                v-model:value="record['columnName']"
                style="width: 100px; margin-right: 5px"
              />
              <Input v-else v-model:value="record['columnName']" />
            </div>

            <div class="w-120px flex items-center">
              <Dropdown :get-popup-container="getPopupContainer">
                <span> {{ record['columnNameTitle'] }} <DownOutlined /> </span>
                <template #overlay>
                  <Menu @click="({ key }) => handleClickMenu(key, record)">
                    <MenuItem :key="k.value" v-for="k in dropdownMenuOptions">
                      {{ k.label }}
                    </MenuItem>
                  </Menu>
                </template>
              </Dropdown>
            </div>
            <Select
              :options="firstBracketOptions"
              v-model:value="record['twoBracket']"
              class="w-80px"
              style="margin-right: 5px"
              :get-popup-container="getPopupContainer"
            />
            <Select
              :options="logicalOptions"
              v-model:value="record['logical']"
              class="w-80px"
              style="margin-right: 5px"
              v-if="index != list.length - 1"
              :get-popup-container="getPopupContainer"
            />
          </div>
        </template>
        <template #action="{ index }">
          <div class="flex">
            <!-- <a-button type="primary" class="mr-2" size="small" @click="handleAdd">新增</a-button> -->
            <a-button type="primary" size="small" @click="handleDelete(index)">删除</a-button>
          </div>
        </template>
      </Table>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, onMounted } from 'vue';
  import { Input, Table, Select, Dropdown, Menu } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { DownOutlined } from '@ant-design/icons-vue';
  import {
    firstBracketOptions,
    columns,
    logicalOptions,
    compareOptions2,
    compareOptions3,
    fieldNameOptions,
    compareOptions,
    columnNameOptions1,
    columnNameOptions2,
    dropdownMenuOptions,
    random,
    handleXML,
    setXML,
    compareOptions4,
  } from './ConfigurationModal.data';
  import { getFormGetFields } from '/@/api/flowManage/flowManage';
  import { useRouter } from 'vue-router';
  import { isArray } from '/@/utils/is';
  import { FormField, WorkflowPredefineDb, ModuleUtil } from '/@/enums/flowManage';
  import { FormCtl } from '/@/components/FormCtl';

  export default defineComponent({
    name: 'ConfigurationModal',
    components: {
      BasicModal,
      Table,
      Select,
      Input,
      DownOutlined,
      Dropdown,
      Menu,
      MenuItem: Menu.Item,
      FormCtl,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const { currentRoute } = useRouter();
      const list = ref<any>([]);
      const getTitle = '条件';
      const formGetFieldsData = ref<Recordable[]>([]);
      const type = ref('');
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: false, width: '80%' });
        try {
          console.log('data', data);
          type.value = data?.type ?? '';
          formGetFieldsData.value = fieldNameOptions;
          if (data?.formGetFieldsData) {
            const newFormGetFieldsData = data.formGetFieldsData.map((item) => {
              return {
                fieldType: item.fieldType,
                formCode: item.formCode,
                value: item.name,
                label: item.title,
              };
            });
            formGetFieldsData.value = [...newFormGetFieldsData, ...fieldNameOptions];
          }
          if (data?.list) {
            list.value = handleXML(data.list);
            list.value.forEach((item) => {
              item.formCode = formGetFieldsData.value.find(
                (el) => el.value == item.fieldName,
              )?.formCode;
            });
            console.log('list.value', list.value);
          } else {
            handleAdd();
          }
        } catch (err) {
          console.log(err);
        }
      });

      async function handleSubmit() {
        try {
          setModalProps({ confirmLoading: true });

          let beginBracketArr: string[] = [];
          let endBracketArr: string[] = [];
          list.value.forEach((item) => {
            for (let v in item) {
              if (item[v] == null || item[v] == 'null') {
                item[v] == '';
              }
            }

            if (item.firstBracket == '(' || item.twoBracket == '(') {
              beginBracketArr.push('(');
            }
            if (item.firstBracket == ')' || item.twoBracket == ')') {
              endBracketArr.push(')');
            }
          });

          console.log('list', list.value);

          if (beginBracketArr.length != endBracketArr.length) {
            createMessage.warning('请检查括弧是否匹配');
            return;
          }
          if (unref(list).length && unref(list).some((item) => !item.compare)) {
            createMessage.warning('请选择比较符号'); // 关系运算符
            return;
          }

          const result = await setXML(unref(list));
          closeModal();
          emit('success', { field: type.value, value: result });
        } catch (err) {
          console.log(err);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      const handleAdd = () => {
        list.value.push({
          id: random(),
          mainColumn: WorkflowPredefineDb.COMB_COND_TYPE_FIELD,
          columnName: '',
          compare: '',
          firstBracket: '',
          value: '',
          twoBracket: '',
          logical: 'and',
          columnNameTitle: '',
          fieldName:
            isArray(formGetFieldsData.value) && formGetFieldsData.value.length
              ? formGetFieldsData.value[0].value
              : '',
        });
        list.value = [...list.value];
        console.log('list.value', list.value);
      };
      const handleDelete = (index) => {
        list.value.splice(index, 1);
        list.value = [...list.value];
      };

      const handleFieldNameChange = (val, record) => {
        console.log('val, record', val, record, formGetFieldsData.value);
        record['compare'] = '';
        record['columnName'] = '';
        record['columnNameTitle'] = '';
        record['fieldName'] = val;
        record['mainColumn'] = WorkflowPredefineDb.COMB_COND_TYPE_FIELD;
        record['fieldType'] = formGetFieldsData.value.find((item) => item.value == val)?.fieldType;
        record['formCode'] = formGetFieldsData.value.find((item) => item.value == val)?.formCode;
        console.log('handleFieldNameChange', record);
      };

      const formGetFieldsMainData = ref<Recordable[]>([]);
      //获取主表字段
      const getFormGetFieldsMainData = () => {
        try {
          const { query } = currentRoute.value;
          if (query?.formCode) {
            getFormGetFields({ formCode: query.formCode }).then((res) => {
              formGetFieldsMainData.value = res || [];
              if (isArray(formGetFieldsMainData.value)) {
                formGetFieldsMainData.value.forEach((item) => {
                  item.value = item.name;
                  item.label = item.title;
                  delete item.options;
                });
              }
            });
          }
        } catch (err) {
          console.log('getFormGetFieldsMainData', err);
        }
      };
      onMounted(() => {
        getFormGetFieldsMainData();
      });

      //点击菜单
      const handleClickMenu = (key, record) => {
        console.log('key', key);
        record['columnName'] = key;
        if (key === 'mainFormOpt') {
          record['columnName'] = formGetFieldsMainData.value[0]?.value;
        } else {
          record['columnName'] = key;
        }
        const obj2 = dropdownMenuOptions.find((k) => k.value == key);
        if (obj2) {
          record['columnNameTitle'] = obj2?.label;
        }
      };

      const getPopupContainer = (triggerNode) => triggerNode?.parentNode;

      return {
        registerModal,
        getTitle,
        handleSubmit,
        list,
        columns,
        firstBracketOptions,
        formGetFieldsData,
        logicalOptions,
        compareOptions2,
        handleAdd,
        handleDelete,
        compareOptions,
        compareOptions3,
        compareOptions4,
        columnNameOptions1,
        columnNameOptions2,
        dropdownMenuOptions,
        handleClickMenu,
        handleFieldNameChange,
        formGetFieldsMainData,
        FormField,
        ModuleUtil,
        getPopupContainer,
      };
    },
  });
</script>
